package crontab

import (
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/utils"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"
)

func SyncAnchorLiveData() {
	var liveStat []models_live.LiveStat

	today := time.Now().Format("2006-01-02")
	// today := day
	yesterday := time.Now().Add(-time.Hour * 24).Format("2006-01-02")
	st, et := utils.OneDayRange2Unix(today)

	err := global2.Live().Model(&models_live.LiveHistory{}).
		Select("anchorid as anchor_id, count(id) as times, sum(end_stamp - start_stamp) as duration, other_gift_price as other_gift").
		Where("end_stamp>=? and end_stamp<=?", st, et).Group("anchorid").
		Scan(&liveStat).Error
	if err != nil {
		global2.Log.Error("SyncAnchorLiveData Get Data error in: %+v", err)
	}

	for _, v := range liveStat {
		//收益
		income, err := db_live.AnchorIncome(v.AnchorID, today)
		if err != nil {
			global2.Log.Error("SyncAnchorLiveData Get Diamond error in: %+v", err)
			v.Diamond = 0
		}
		v.Diamond = income.Income
		v.OtherGift = income.EagleDiamond

		var newFans int64
		// 当日新增
		global2.Live().Model(&models_main.AnchorFans{}).Where("anchorid=? and create_time>=? and create_time<=?", v.AnchorID, today, today+" 23:59:59").Count(&newFans)
		v.NewFans = int(newFans)

		// 当前日总粉丝总数
		err = global2.Live().Model(&models_main.AnchorFans{}).
			Select("count(id) as total_fans").Where("anchorid=? and create_time<=?", v.AnchorID, today+" 23:59:59").
			Scan(&v).Error
		if err != nil {
			global2.Log.Error("SyncAnchorLiveData Get TotalFans Data error in: %+v", err)
		}
		// 一天流失
		var yesterdayTotalFans int
		err = global2.Live().Model(&models_live.LiveStat{}).
			Where("anchor_id=? and date=?", v.AnchorID, yesterday).
			Pluck("total_fans", &yesterdayTotalFans).Error
		if err != nil {
			global2.Log.Error("SyncAnchorLiveData Get LostFans Data error in: %+v", err)
		}
		v.LostFans = yesterdayTotalFans - v.TotalFans
		// 如果今天比昨天多流失数为负数直接为0
		if v.LostFans < 0 {
			v.LostFans = 0
		}

		// 观众
		var visitor int64
		err = global2.Live().Model(&models_live.LiveStreamHistory{}).Where("anchorid=? and last_visit_time>=? and last_visit_time<=?", v.AnchorID, st, et).Group("liveid").Count(&visitor).Error
		if err != nil {
			global2.Log.Error("SyncAnchorLiveData Get Visitor Data error in: %+v", err)
		}
		v.Visitor = int(visitor)

		v.Date, _ = time.Parse("2006-01-02", today)
		global2.Live().Model(&models_live.LiveStat{}).Where("anchor_id=? and date=?", v.AnchorID, today).Delete(&v) //如出现重复执行数据直接删除覆盖
		err = global2.Live().Model(&models_live.LiveStat{}).Create(&v).Error
		if err != nil {
			global2.Log.Error("SyncAnchorLiveData Create Data error in: %+v", err)
		}
	}
}
